package com.work.filter;


import com.work.pojo.User;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.io.IOException;
import java.util.HashMap;


/**
 * @ClassName: LoginFilter
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/21  19:47
 * 加入购物车的过滤器
 */

@WebFilter(urlPatterns = {"/pushcar","/showcar", "/clearcar", "/deletegood"})
public class PushCarFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String Path = request.getServletPath();
        switch (Path){
            case "/pushcar":
                pushCar(request,response,chain);
                break;
                //对被挤下线的客户端当进行操作时，进行过滤，提示用户已被挤下线，引导用户登录
            default:leadLogin(request,response,chain);
        }



    }

    @Override
    public void destroy() {

    }

    private void pushCar(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
        //判断当前用户是否登陆
        User user = (User) request.getSession().getAttribute("state");
        String goodId = request.getParameter("goodId");
        String mynum = request.getParameter("num");
        if (mynum == null) {
            mynum = "1";
        }
        int num = Integer.parseInt(mynum);
        int good_id = Integer.parseInt(goodId);
        //判断条件
        if (user != null) {
            chain.doFilter(request,response);
        } else {
            //用户未登录，存储用户的购物车信息放入Session中
            HashMap<Integer, Integer> hashmap = (HashMap<Integer, Integer>) request.getSession().getAttribute("hashmap");
            hashmap.put(good_id, num);

            request.getSession().setAttribute("hashMapGoods", hashmap);
            //引导用户去登录
            response.setContentType("text/HTML;charset=utf-8");
            response.getWriter().write("<script>alert('请您先登录！');location.href='/login.jsp';</script>");
        }
    }


    private void leadLogin(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws IOException, ServletException {
        User user = (User) request.getSession().getAttribute("state");
        if (user != null) {
            chain.doFilter(request,response);
        } else {
            //用户未登录，存储用户的购物车信息放入Session中
            //引导用户去登录
            response.setContentType("text/HTML;charset=utf-8");
            response.getWriter().write("<script>alert('您的账号已在其他设备登录，您强制下线！');location.href='/login.jsp';</script>");
        }
    }


}
